// pages/myself/myself.js
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: wx.getStorageSync('userInfo'),
        recordDetail: {}
    },

    back: function () {
        //清理缓存
        wx.clearStorageSync("token")
        wx.clearStorageSync('userInfo')
        wx.showModal({
            title: '提示',
            content: '真的要退出了吗',
            cancelText: '不是',
            confirmText: '是的',
            confirmColor: '#000000',
            cancelColor: '#576b95',
            success(res) {
                if (res.confirm) {                 
                    wx.reLaunch({
                        url: '/pages/login/login',
                    })
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },

    getRecord: function () {
        var that = this
        wx.request({
            url: app.globalData.requestContext + '/listRecord',
            method: "POST",

            header: {
                'content-type': "application/x-www-form-urlencoded",
                'token': wx.getStorageSync("token")
            },
            success: function (res) {
                var records = res.data.data //打卡记录
                for (let index = 0; index < records.length; index++) {
                    records[index].startTime = that.getDate(records[index].startTime)
                    records[index].endTime = that.getDate(records[index].endTime)

                }
                that.setData({
                    punchRecords: records
                })
            }


        })
    },
    saveWxInfo:function(){
        wx.login({            
            success:function(res){
                console.log("res的code:" + res.code)
                wx.request({
                  url: app.globalData.requestContext + '/wxInfo',
                  method:'GET',
                  header:{
                      'content-type': "application/json" ,// 默认值
                      'token': wx.getStorageSync("token")
                  },
                  data:{
                      code:res.code
                  },
                  success:function(res){
                      console.log(res.data.msg)
                  }

                })
            }
          })
    },

    getDate: function (unixtime) {
        var dateTime = new Date(parseInt(unixtime) * 1000)
        var year = dateTime.getFullYear();
        var month = dateTime.getMonth() + 1;
        var day = dateTime.getDate();
        var hour = dateTime.getHours();
        var minute = dateTime.getMinutes();
        var second = dateTime.getSeconds();
        var now = new Date();
        var now_new = Date.parse(now.toDateString()); //typescript转换写法
        var milliseconds = now_new - dateTime;
        var timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
        return timeSpanStr;
    },

    jilu: function () {
        // wx.navigateTo({
        //     url: '../notes/notes',
        // })
        wx.navigateTo({
            url: '/pages/note/note',
        })
    },

    oninfo(event) {
        console.log(event)
        // if (event.detail.userInfo){
        // //用户点击了确认授权event.detail.userInfo中就会有个人信息，
        // //如果没有就是用户点击了拒绝授权，当用户成功授权后
        // //再次点击按钮将不会弹出授权框，如果拒绝，再次点击会继续弹出授权框
        //   console.log('用户确认授权')
        // }else{
        //   console.log('用户拒绝授权')
        // }
    },
    toProcessCheckOutPage:function(){
        wx.navigateTo({
          url: '/pages/notice/notice',
        })
    },
    toApplyPage:function(){
        var that = this
        wx.request({
            url: app.globalData.requestContext + '/getSignOutStatus',
            method: 'GET',
            header: {
                'content-type': "application/json", // 默认值
                'token': wx.getStorageSync("token")
            },
            success: function (res) {
                if(res.data.code == 0){
                    wx.navigateTo({
                      url: '/pages/applySignOut/applySignOut',
                    })
                }else if(res.data.code == 0){
                    wx.showToast({
                      title: res.data.msg,
                      icon:'none'
                    })
                }else{
                    wx.showToast({
                        title: res.data.msg,
                        icon:'none'
                      })
                }
            }
        })
    },
    getRecordDetail: function () {
        var that = this
        wx.request({
            url: app.globalData.requestContext + '/recordDetail',
            method: 'GET',
            header: {
                'content-type': "application/json", // 默认值
                // 'cookie': wx.getStorageSync("sessionid"), //读取sessionid,当作cookie传入后台将PHPSESSID做session_id使用
                'token': wx.getStorageSync("token")
            },
            success: function (res) {
                if (res.data.code == 0) {
                    that.setData({
                        recordDetail: res.data.data
                    })
                } else if (res.data.code == 3) {
                    wx.reLaunch({
                        url: '/pages/login/login',
                    })
                } else {
                    wx.showToast({
                        title: res.data.msg,
                        icon: "error"
                    })
                }
            }
        })
    },
    tomanagePage: function () {
        wx.navigateTo({
            url: '/pages/manager/manager',
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(e) {
        
        this.getRecordDetail()
        this.setData({
            userInfo:wx.getStorageSync('userInfo')
        })
        if (this.data.userInfo.nickName == null || this.data.userInfo.avatarUrl == null) {
            this.setUserInfoStorageTime();
        }
        if (this.data.userInfo.nickName == '微信用户' ) {
            this.setUserInfoStorageTime();
        }
         this.saveWxInfo()

    },
    getUserProfile() {
        var that = this;
        wx.showModal({
            title: "提示",
            content: "是否允许获取微信昵称和头像？",
            success(res) {
                if (res.confirm) {
                   

                    wx.getUserProfile({
                        desc: "用于完善用户资料", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
                        success: (res) => {
                            console.log(res)
                            app.globalData.userInfo = res.userInfo; //这个我有时候获取不到，所以没管它，但先写着
                            that.setData({
                                userInfo: res.userInfo
                            });
                            wx.setStorageSync("userInfo", res.userInfo);

                            let setNowTime = Date.now() + 3600 * 1000 * 24 * 30; // 我设置了30天有效期，你们可以自己改
                            wx.setStorageSync("userInfoStorageTime", setNowTime);
                        },
                        fail: function (err) {
                            console.log(err);
                        },
                    });
                }
            },
        });
    },
    setUserInfoStorageTime() {

        var that = this;
        let nowTime = Date.now();
        let oldTime = wx.getStorageSync("userInfoStorageTime");
        let userInfo = wx.getStorageSync("userInfo");
        if (userInfo.nickName != undefined && userInfo.nickName != null && userInfo.nickName != "") {
            that.setData({
                userInfo: {
                    nickName: '微信用户',
                    avatarUrl: 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132'
                }
            })

            if (oldTime && nowTime < oldTime) {
                wx.setStorageSync('userInfo', that.data.userInfo)
                that.setData({
                    userInfo: userInfo
                })
                return;
            } else {
                that.getUserProfile();
            }
        } else {
            that.getUserProfile();
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getRecordDetail()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})